var _treeDatagrid,dialogAddRow,formAddRow,iconDialog,pid,id,checked,text,orderIndex,url,iconCls;

function addRow(o) {
	if (o && o != undefined) {
		_treeDatagrid.treegrid('select', o);
	}
	addRowHandler();
}

function addRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
	if (node && node.length > 0) {
		if (node.length > 1) {
			$.messager.alert('提示', '您选择了多个菜单项,只能选择一个菜单项！', 'warning');
			_treeDatagrid.treegrid('unselectAll');
		} else {
			pid.combotree('setValue', node[0].id).combotree('setText', node[0].text).combotree('disable');
			id.val(node[0].id);
			checked.combobox('setValue','');
			text.val('');
			orderIndex.numberspinner('setValue', 1);
			url.val('');
			iconCls.val('');
			dialogAddRow.dialog({title : '添加菜单项', iconCls : 'icon-add', buttons : [{text : '添加',	handler : dialogEnterHandler}]});
			dialogAddRow.dialog('open');
		}
	} else {
		$.messager.alert('提示', '您没有选择菜单项,请选择父节点！', 'warning');
	}
}

function deleteRow(o) {
	if (o && o != undefined) {
		_treeDatagrid.treegrid('select', o);
	}
	deleteRowHandler();
}

function deleteRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
	if (node && node.length > 0) {
		$.messager.confirm('请确认', '您确实要删除当前所有选择的记录吗？\n注意：此操作将删除该菜单下的所有子菜单！！！', function(b){
			if (b) {
				var ids = [];
				for ( var i = 0; i < node.length; i++) {
					if (node[i].id == 1) {
						$.messager.alert('警告', "对不起,您不能删除根节点!", 'warning');
						return ;
					}
					ids.push(node[i].id);
				}
				$.post(sy.bp()+"/admin/systemNavigation/delete", {ids:ids.join(",")}, function(data) {
					if (data.result==1) {
						$.messager.show({msg:data.msg,title:'系统提示'});
						_treeDatagrid.treegrid('unselectAll');
						_treeDatagrid.treegrid('reload');
						pid.combotree('reload');
					} else {
						$.messager.alert('警告', data.msg, 'warning');
					}
				}, "json");
			}
		});
	} else {
		$.messager.alert('提示', '请选择要删除的记录', 'error');
	}
}

function updateRow(o) {
	if (o && o != undefined) {
		_treeDatagrid.treegrid('select', o);
	}
	updateRowHandler();
}

function updateRowHandler() {
	var node = _treeDatagrid.treegrid('getSelections');
	if (node && node.length > 0) {
		if (node.length > 1) {
			$.messager.alert('提示', '您选择了多个菜单项,只能选择一个菜单项！', 'warning');
			_treeDatagrid.treegrid('unselectAll');
		} else {
			if (node[0].id == 1) {
				$.messager.alert('提示', '您不能修改根节点!', 'warning');
				return;
			}
			pid.combotree('setValue', node[0].pid).combotree('setText', node[0].ptext).combotree('enable');
			id.val(node[0].id);
			checked.combobox('setValue', node[0].checked);
			text.val(node[0].text);
			orderIndex.numberspinner('setValue', node[0].orderIndex);
			url.val(node[0].url);
			iconCls.val(node[0].iconCls);
			dialogAddRow.dialog({title : '更新菜单项', iconCls : 'icon-edit', buttons : [{text : '更新',	handler : dialogEnterHandler}]});
			dialogAddRow.dialog('open');
		}
	} else {
		$.messager.alert('提示', '您没有选择菜单项,请选择！', 'warning');
	}
}

function reloadRow() {
	_treeDatagrid.treegrid('reload');
}

function unselectRow() {
	_treeDatagrid.treegrid('unselectAll');
}

function dialogEnterHandler() {
	var pathUrl = sy.bp() + '/admin/systemNavigation/';
	var datas = formAddRow.serialize();
	if (formAddRow.form('validate')) {
		if (id.val() == pid.combotree('getValue')) {
			pathUrl += 'add';
			datas = '&pid=' + id.val() + '&' + datas;
		} else {
			pathUrl += 'update';
		}
		$.post(pathUrl, datas, function(data){
			if(data && data.result ==1) {
				dialogAddRow.dialog('close');
				$.messager.show({title:'系统提示', msg:data.msg, timeout:2000, showType:'slide'});
				_treeDatagrid.treegrid('reload');
				pid.combotree('reload');
			} else {
				$.messager.alert('错误提示', data.msg);
			}
		},"json");
	}
}

$(function() {
	_treeDatagrid = $('#_treeDatagrid');
	dialogAddRow = $('#dialogAddRow');
	formAddRow = $('#formAddRow');
	iconDialog = $('#iconDialog');
	pid = $('#pid');
	id = $('#id');
	checked = $('#checked');
	text = $('#text');
	orderIndex = $('#orderIndex').numberspinner({editable: false}).numberspinner('setValue', 1);
	url = $('#url');
	iconCls = $('#iconCls');
	
	/*初始化添加菜单对话框中的form*/
	formAddRow.form({});
	
	/*设置checked.combobox点击输入框弹出面板*/
	checked.combobox('activeTextArrow');
	
	pid.combotree({required:true,editable:false,url:sy.bp()+"/admin/systemNavigation/listTreegrid"}).combotree('activeTextArrow');
	text.validatebox({required:true,validType:['unnormal','maxLength[50]']});
	url.validatebox({validType:['unnormal','maxLength[200]']});
	
	/*初始化添加菜单对话框*/
	dialogAddRow.show().dialog({resizable : false, closed : true, closable : true, modal : true});
	
	/*绑定添加菜单对话框回车事件*/
	dialogAddRow.keydown(function(event){if(event.keyCode==13){dialogEnterHandler();}});
	
	/*绑定选择图标事件*/
	iconCls.click(function() {iconDialog.dialog('open');}).mouseover(function() {this.style.cursor='not-allowed';});
	
	/*初始化选择图标对话框*/
	iconDialog.show().dialog({
		iconCls: 'icon-application_view_icons',  
        href: sy.bp() + '/resources/esayUI/1.3.2/themes/iconlist.htm',
        title: '选取图标',
        width: 640,
        height: 480,
        closed : true,
        onLoad: function () {$('#iconlist li').attr('style', 'float:left;border:1px solid #fff;margin:2px;width:16px;cursor:pointer').click(function () {iconCls.val($(this).attr('class'));iconDialog.dialog('close');}).hover(function () {$(this).css({ 'border': '1px solid red' });}, function () {$(this).css({ 'border': '1px solid #fff' });});}
	});
		
	/*初始化菜单treegrid*/
	_treeDatagrid.treegrid({   
	    url: sy.bp()+'/admin/systemNavigation/listTreegrid',
	    idField:'id',
	    treeField:'text',
	    fit : true,
		autoRowHeight : true,
		striped : true,
		rownumbers : true,
		singleSelect : true,
		fitColumns : true,
		nowrap : true,
		border : false,
		toolbar: [
					{text:'增加',iconCls: 'icon-add',handler: addRowHandler},'-',
					{text:'批量删除',iconCls: 'icon-remove',handler: deleteRowHandler},'-',
					{text:'修改',iconCls: 'icon-edit',handler: updateRowHandler},'-',
					{text:'取消选中',iconCls: 'icon-redo',handler: unselectRow},'-',
					{text:'刷新',iconCls: 'icon-reload',handler: reloadRow},'-'
				 ],
	    columns:[[
	    	{field:'text',title:'菜单名称',width:500,align:'left'},
	        {field:'url',title:'URL',width:500,align:'left'},
	        {field:'orderIndex',title:'排序',width:100,align:'center'}
	    ]],
	    onLoadSuccess : function(data) {
			_treeDatagrid.treegrid('expand', 1);
			//_treeDatagrid.treegrid('expandAll');
			$.messager.progress('close');
		},
		onDblClickRow : function(row){
			_treeDatagrid.treegrid('toggle', row.id);
			
		},
		onContextMenu : function(e, row){
			_treeDatagrid.treegrid('unselectAll');
			_treeDatagrid.treegrid('select', row.id);
			e.preventDefault();
			$('#treeridContextMenu').menu('show', {left:e.pageX,top:e.pageY});
		}
	});
});